package com.itheima.reggie.controller;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @author 黑马程序员
 */
@RestController
@Slf4j
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    //注入业务类
    @Autowired(required = false)
    private ShoppingCartService shoppingCartService;


    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart, HttpSession session){

        //1.获取登录用户id
        User user = (User) session.getAttribute("user");

        //2.调用业务添加购物车操作(返回的购物车数据里面带有最新的份数)
        shoppingCart = shoppingCartService.add(shoppingCart,user.getId());

        return R.success(shoppingCart);
    }


    //查询用户购物车记录列表
    @GetMapping("/list")
    public R<List<ShoppingCart>> add(HttpSession session){

        //1.获取登录用户id
        User user = (User) session.getAttribute("user");

        //2.根据用户id查询用户的购物车列表集合
        List<ShoppingCart> shoppingCartList = shoppingCartService.findAllByUid(user.getId());

        return R.success(shoppingCartList);
    }

    //删除用户购物车记录数据
    @DeleteMapping("/clean")
    public R<String> clean(HttpSession session){

        //1.获取登录用户id
        User user = (User) session.getAttribute("user");

        //2.根据用户id删除所有购物车记录数据
        shoppingCartService.clean(user.getId());

        return R.success("清空成功");
    }

    //购物车减少购买数量
    @PostMapping("/sub")
    public R<String> sub(@RequestBody ShoppingCart shoppingCart ,HttpSession session){
        //1.获取登录用户id
        User user = (User) session.getAttribute("user");
        shoppingCart.setUserId(user.getId());
        shoppingCartService.sub(shoppingCart);
        return R.success("订单减少成功");
    }
}
